async = require 'async'
cheerio = require 'cheerio'
fs = require 'fs'
got = require 'got'
path = require 'path'

commonHeaders = require './common-headers'
saveAlbum = require './album'

saveAlbums = module.exports = (cookie, dist, { userId }) ->
  headers = {
    'Cookie': cookie
    ...commonHeaders
  }
  albumsUrl = "http://photo.renren.com/photo/#{userId}/album/relatives"
  resp = await got albumsUrl, { headers }

  photoNumTxt = cheerio('.album-main .numbers', resp.body).text()
  [photoNumber] = photoNumTxt.match /\d+/
  throw new Error("No photos: #{photoNumTxt}") unless photoNumber

  try
    resp = await got "#{albumsUrl}/ajax?offset=0&limit=#{photoNumber}", { headers }
  catch err
    throw new Error("fetching album home of #{userId}: #{err}")

  $ = cheerio.load "<ul>#{resp.body}</ul>"

  albumUrls = $('a.album-title').map -> $(@).attr('href')
  concurrentLv = 5
  async.mapLimit albumUrls, concurrentLv, (plainAlbumUrl) ->
    [_, userId, albumId] = plainAlbumUrl.match /(\d+)\/album-(\d+)/

    throw new Error("Unrecognized url: #{plainAlbumUrl}") if not userId or not albumId

    try
      await saveAlbum cookie, dist, { userId, albumId }
      console.log "saved #{albumId} of #{userId}"
    catch err
      console.error "error getting #{albumId}: #{err}"

unless module.parent
  [_, _, userId] = require('process').argv
  if not userId
    return console.error 'no user is provided.'
  cookie = fs.readFileSync path.join __dirname, '..', 'config', 'cookie'
  saveAlbums cookie, 'cache', { userId }
